namespace NHCodeFirst.Helpers
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Linq.Expressions;
    using System.Reflection;

    public class ExpressionHelper : ExpressionVisitor
    {
        private readonly List<string> properties = new List<string>();
        public string GetPropertyName(Expression expression)
        {
            properties.Clear();
            Visit(expression);
            return string.Join(".", Enumerable.Reverse(properties));
        }

        public string GetPropertyName<T, TResult>(Expression<Func<T, TResult>> expression)
        {
            properties.Clear();
            Visit(expression);
            return string.Join(".", Enumerable.Reverse(properties));
        }

        protected override Expression VisitMember(MemberExpression node)
        {
            if (node.Member.MemberType == MemberTypes.Property)
                properties.Add(node.Member.Name);
            return base.VisitMember(node);
        }
    }
}